﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Text.RegularExpressions;
using System.Text;

public class EmojiInputField : InputField
{
    private string m_OriginalStr;
    private string m_TranslatedStr;
    private bool m_IsActivatingKeyboard = false;

    List<string> patterns = new List<string>();

    public string OriginalText
    {
        get
        {
#if UNITY_EDITOR
            return text;
#else
            return m_OriginalStr;
#endif
        }

        set
        {
            m_OriginalStr = value;
            m_TranslatedStr = EmojiTranslate.Translate(m_OriginalStr);
            text = m_TranslatedStr;
        }

    }

    protected override void Awake()
    {
        base.Awake();
        patterns.Add(@"\p{Cs}");
        patterns.Add(@"[\u2702-\u27B0]");
    }

    protected override void LateUpdate()
    {
#if !UNITY_EDITOR
        if(isFocused)
        {
            m_Text = m_Keyboard.text;//正在编辑的过程中屏蔽Unity更新UI文字的功能，应为这里可能输入Emoji导致Unity报错
        }
#endif

        base.LateUpdate();

#if !UNITY_EDITOR
        if (m_IsActivatingKeyboard)
        {
            if (m_Keyboard != null)
            {
                m_Keyboard.text = m_OriginalStr;
                m_IsActivatingKeyboard = false;
            }
        }

        if (m_Keyboard != null)
        {
            m_OriginalStr = m_Keyboard.text;
        }
#endif
    }

    public override void OnSelect(BaseEventData eventData)
    {
        base.OnSelect(eventData);

#if !UNITY_EDITOR
        m_IsActivatingKeyboard = true;
#endif
    }

    public override void OnDeselect(BaseEventData eventData)
    {
        base.OnDeselect(eventData);

#if !UNITY_EDITOR
        string translatedText = EmojiTranslate.Translate(m_OriginalStr);
        StringBuilder sb = new StringBuilder();
        foreach(char c in translatedText)
        {
            if(BEmoji(string.Format("{0}", c)) == false)
            {
                sb.Append(c);
            }
        }
        m_Text = "";
        m_TranslatedStr = sb.ToString();
        text = m_TranslatedStr;
#endif
    }

    private bool BEmoji(string s)
    {
        bool bEmoji = false;
        for (int i = 0; i < patterns.Count; ++i)
        {
            bEmoji = Regex.IsMatch(s, patterns[i]);
            if (bEmoji)
            {
                break;
            }
        }
        return bEmoji;
    }
}
